<script setup lang="ts">
import { reactive, ref, onBeforeMount, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store'
import { md5Encrypt, AesDecryptHex } from '@/common/utils'
import type { FormInstance } from 'element-plus'
import { getLoginPicCaptcha, loginByAccount, getSuccessStatus } from '@/api/login'

const router = useRouter()
const route = useRoute()

const userStore = useUserStore()

const formState: LoginFormInfoType = reactive({
	username: '',
	password: '',
	verifyCode: '',
	remember: true,
})

const isLoading = ref(false)

const formRef = ref<FormInstance>()

const verifyPic = ref<string>('')
const verifyCodeKey = ref<string>('')
const verifyCodeValue = ref<string>('')
let inputList: NodeListOf<HTMLElement>

const rules = {
	userName: [{ required: true, message: '请输入你的用户名!', trigger: 'blur' }],
	password: [{ required: true, message: '请输入你的密码!', trigger: 'blur' }],
	verifyCode: [{ required: true, message: '请输入你的验证码!', trigger: 'blur' }],
}

onBeforeMount(() => {
	console.log('超级管理员账号：admin，密码：admin')
	bindToggleVerifyPic()
	const { remember, username, password } = userStore.loginInfo
	if (remember && username && password) {
		formState.username = username
		formState.password = password
		formState.remember = remember
	}
	if (typeof remember == 'boolean') formState.remember = remember
})

onMounted(() => {
	inputList = document.querySelectorAll('.account-form .el-input__inner')
	inputList[0].focus()
})

function resetForm(formEl: FormInstance | undefined) {
	if (!formEl) return
	formEl.resetFields()
}

function handleInputsKeyDown(e: KeyboardEvent) {
	if (e.key == 'ArrowUp' || e.key == 'ArrowDown') e.preventDefault()
}

function handleInputsKeyUp(index: number, e: KeyboardEvent) {
	if (e.key == 'Enter') submitForm(formRef.value)
	const toggleFocus = (direction: 'down' | 'up') => {
		let i: number
		if (direction == 'up') {
			i = index - 1
			if (i < 0) i = inputList.length - 1
		} else {
			i = index + 1
			if (i > inputList.length - 1) i = 0
		}
		inputList[i].focus()
	}
	if (e.key == 'ArrowUp') {
		toggleFocus('up')
	}
	if (e.key == 'ArrowDown') {
		toggleFocus('down')
	}
}

async function bindToggleVerifyPic() {
	const res = await getLoginPicCaptcha()
	if (res.code == getSuccessStatus()) {
		const { codeKey, codeVlaue, base64 } = res.data
		verifyCodeKey.value = AesDecryptHex(codeKey)
		verifyPic.value = base64
	}
}

async function submitForm(formEl: FormInstance | undefined) {
	if (isLoading.value) return
	await formEl?.validate()
	isLoading.value = true
	const params = { username: formState.username, password: md5Encrypt(formState.password), codeKey: verifyCodeKey.value, codeValue: formState.verifyCode }
	const res = await loginByAccount(params)
	isLoading.value = false
	console.log(res)
	if (res.code == getSuccessStatus()) {
		await userStore.login(res.data.token)
		const { id } = userStore.loginInfo
		if (route.query.redirect && res.data.id === id)
			// 防止重定向到没有权限的页面
			router.push(decodeURIComponent(route.query.redirect as string))
		else router.push('/')
		if (formState.remember) {
			userStore.$patch((s) => {
				const {
					loginInfo: { phone },
				} = s
				const obj: LoginFormInfoType = { phone, id: res.data.id, activeTab: 'account', ...formState }
				delete obj.verifyCode
				s.loginInfo = obj
			})
		} else {
			userStore.$patch((s) => {
				const {
					loginInfo: { phone },
				} = s
				s.loginInfo = { password: '', username: '', remember: false, phone, id: res.data.id, activeTab: 'account' }
			})
		}
	}
	// 一个验证码只使用一次，无论成功失败
	bindToggleVerifyPic()
}
</script>

<template>
	<el-form class="account-form" status-icon ref="formRef" :model="formState" :rules="rules">
		<el-form-item prop="username">
			<el-input v-model="formState.username" placeholder="用户名" clearable prefix-icon="User" @keyup="handleInputsKeyUp(0, $event)" @keydown="handleInputsKeyDown"></el-input>
		</el-form-item>

		<el-form-item prop="password">
			<el-input
				v-model="formState.password"
				placeholder="密码"
				type="password"
				show-password
				clearable
				prefix-icon="Lock"
				@keyup="handleInputsKeyUp(1, $event)"
				@keydown="handleInputsKeyDown"
			></el-input>
		</el-form-item>

		<el-form-item prop="verifyCode">
			<el-input
				v-model="formState.verifyCode"
				placeholder="请输入验证码"
				prefix-icon="Key"
				style="width: 60%; margin-right: 10px"
				@keyup="handleInputsKeyUp(2, $event)"
				@keydown="handleInputsKeyDown"
			></el-input>
			<img style="width: 35%; height: 32px" :src="verifyPic" @click="bindToggleVerifyPic" />
		</el-form-item>

		<el-form-item label="" prop="remember">
			<div style="width: 100%">
				<el-checkbox v-model="formState.remember">记住密码</el-checkbox>
				<el-link type="primary" class="login-form-forgot" href="javascript:;" :underline="false">忘记密码</el-link>
			</div>
		</el-form-item>

		<el-form-item>
			<el-button style="width: 100%" type="primary" @click="submitForm(formRef)" :loading="isLoading">登录</el-button>
			<!-- <el-button @click="resetForm(formRef)">Reset</el-button> -->
		</el-form-item>
	</el-form>
</template>

<style scoped lang="scss">
.login-form-forgot {
	float: right;
}
</style>
